#模板匹配  霍夫线检测
#霍夫线检测要求图像必须是二值化图像  可以在canny边缘检测后
#霍夫圆检测
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt

img=cv.imread("F:\\11\\model\\oringin.png")
model=cv.imread("F:\\11\\model\\after.png")
h,w,l=model.shape
#method=CV.TM_SQDIFE/CV.TM_CCORR/CV.TM_CCOEFF
method=cv.TM_CCOEFF;
def Canny(img):
    lowThreshold=0;
    max_lowThreshold=100;
    canny=cv.Canny(img,lowThreshold,max_lowThreshold)
    return canny;
def Houghlines():#霍夫线检测
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    edges = cv.Canny(gray, 50, 100)
    lines=cv.HoughLines(edges,0.8,np.pi/180,150)
    for line in lines:
        rho,theta=line[0]
        a=np.cos(theta)
        b=np.sin(theta)
        x0=a*rho
        y0=b*rho
        x1=int(x0+1000*(-b))
        y1=int(y0+1000*(a))
        x2=int(x0-1000*(-b))
        y2=int(y0-1000*(a))
        Houghlines=cv.line(img,(x1,y1),(x2,y2),(0,255,0))
        return  Houghlines;
def Match(method):#进行模板的匹配
    res=cv.matchTemplate(img,model,method)
    min_val,max_val,min_loc,max_loc=cv.minMaxLoc(res)
    #使用平方差时最小值为最佳匹配位置
    top_left=max_loc
    bottom_right=(top_left[0]+w,top_left[1]+h)
    result=cv.rectangle(img,top_left,bottom_right,(0,255,0),2)
    return result
def Houghcircle(method):#霍夫圆检测
    gay_img=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    img1=cv.medianBlur(gay_img,7)
    circles=cv.HoughCircles(img1,method,dp=1,minDist=200,param1=100,param2=100,minRadius=0,maxRadius=0)
    for i in circles[0,:]:#遍历矩阵所有的数据
        cv.circle(img,(i[0],i[1],),i[2],(0,255,0),2)#绘制圆形
        cv.circle(img,(i[0],i[1]),2,(0,255,0),3)#绘制圆心
        return img
def show(img,img1):
    plt.figure(figsize=(10,8),dpi=100)
    plt.subplot(121),plt.imshow(img[:,:,::-1]),plt.title('origin')
    plt.xticks([]),plt.yticks([])
    plt.subplot(122),plt.imshow(img1[:,:,::-1]),plt.title('after')
    plt.xticks([]),plt.yticks([])
    plt.show()
if __name__=="__main__":
    #show(img,Match(method))
    #show(img,Houghlines())
    show(img,Houghcircle(cv.HOUGH_GRADIENT))
